package com.cyq.controller;

import com.cyq.config.UserRealm;
import com.cyq.pojo.User;
import com.cyq.service.UserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.mgt.DefaultSecurityManager;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;

@Controller
@RequestMapping("/login")
public class LoginController {

    @Autowired
    private UserService userService;

    /*跳转到用户登录页面*/
    @RequestMapping("/toLogin")
    public String toLogin(){
        return "index";
    }

    /*用户登录*/
    @PostMapping("/login")
    public ModelAndView login(User user, HttpServletRequest request){
        ModelAndView mav = new ModelAndView();

        DefaultSecurityManager securityManager = new DefaultSecurityManager();
        UserRealm realm = new UserRealm();
        securityManager.setRealm(realm);
        SecurityUtils.setSecurityManager(securityManager);

        //获取当前用户
        Subject subject = SecurityUtils.getSubject();
        //封装用户的登录数据，这里的token是全局变量，可以在任意位置取出
        UsernamePasswordToken token = new UsernamePasswordToken(user.getUserCode(), user.getUserPassword());
        //执行登录的方法
        try {
            subject.login(token);
            User user1 = userService.queryUserByUser(user);
            request.getSession().setAttribute("username",user1.getUserName());
            mav.addObject("name",user1.getUserName());
            mav.setViewName("redirect:/main.html");
        } catch (UnknownAccountException e) {    //捕获用户名不存在的异常
            mav.addObject("msg","用户名错误");
            mav.setViewName("/index");
        } catch (IncorrectCredentialsException e) { //捕获密码错误的异常
            mav.addObject("msg","密码错误");
            mav.addObject("userCode",user.getUserCode());
            mav.setViewName("/index");
        }
        return mav;
    }

    /*用户注销：交给shiro完成，在shiroConfig中配置即可*/
    /*@GetMapping("/logout")
    public ModelAndView logout(HttpSession session){
        ModelAndView mav = new ModelAndView();
        session.invalidate();
        mav.addObject("msg","已注销，请重新登录");
        mav.setViewName("index");
        return mav;
    }*/
}
